package com.project.scheduled.aop;

import com.project.scheduled.service.TjDay1LogService;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class BusinessLogicServiceAspect {
    @Resource
    private TjDay1LogService tjDay1LogService;

    @Around("@annotation(logExecution)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint, LogExecution logExecution) throws Throwable {
        String methodName = logExecution.value().isEmpty() ? joinPoint.getSignature().getName() : logExecution.value();
        LocalDateTime now = LocalDateTime.now();

        // 记录开始日志
        tjDay1LogService.saveLog(0, null, now, methodName);

        long startTime = System.currentTimeMillis();
        Object result = null;
        Exception exception = null;

        try {
            result = joinPoint.proceed();
            return result;
        } catch (Exception e) {
            exception = e;
            throw e;
        } finally {
            long endTime = System.currentTimeMillis();
            if (exception != null) {
                // 记录异常日志
                tjDay1LogService.saveLog(9, null, LocalDateTime.now(), methodName + "执行异常:" + exception.getMessage());
                log.error("{}执行异常:"+exception, methodName);
            } else {
                // 记录结束日志
                tjDay1LogService.saveLog(1, null, LocalDateTime.now(), methodName);
                log.info("{} cost time:{}", methodName, (endTime - startTime));
            }
        }
    }
}
